package com.mall.seckill_mall.rabbitmq.sender;

import com.mall.seckill_mall.common.RabbitConstants;
import com.mall.seckill_mall.common.SeckillMessage;
import com.mall.seckill_mall.utils.JsonUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MQProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendOrder(String msg, int ttl) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //发送消息-->交换机：订单交换机；路由键：订单路由键
        rabbitTemplate.convertAndSend(RabbitConstants.ORDER_EXCHANGE, "order", msg, message -> {
            System.out.println("订单将在1分钟过期！" + sdf.format(new Date()) + "----> send");
            message.getMessageProperties().setExpiration(String.valueOf(ttl));
            return message;
        });
    }

    public void sendSeckill(SeckillMessage seckillMessage, int ttl) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //发送消息-->交换机：订单交换机；路由键：订单路由键
        rabbitTemplate.convertAndSend(RabbitConstants.SEKILL_EXCHANGE, RabbitConstants.SEKILL_ROUTING_KEY, JsonUtils.beanToString(seckillMessage), message -> {
            System.out.println("秒杀中！" + sdf.format(new Date()) + "----> send");
            message.getMessageProperties().setExpiration(String.valueOf(ttl));
            return message;
        });
    }

//    public void sendTest(String msg) {
//        rabbitTemplate.convertAndSend("test_ex", "test", msg);
//    }
}
